<template>
	<view class="order-segment-page">
		<!-- 分段器 -->
		<view class="segment-control">
		  <view
			:class="currentSegment === 1 ? 'segment-item active' : 'segment-item'"
			@click="switchSegment(1)">
			创建订单
		  </view>
		  <view
			:class="currentSegment === 2 ? 'segment-item active' : 'segment-item'"
			@click="switchSegment(2)">
			我的订单
		  </view>
		</view>
		<view v-if="currentSegment === 1" class="order-list">
			<!-- 表单容器 -->
			<view class="form">
			  <!-- 从哪儿出发 -->
			  <view class="form-item">
				<view class="form-label">从哪儿出发:</view>
				<input 
				  v-model="model1.startAddress" 
				  placeholder="请输入出发地址"
				  class="form-input"
				  @blur="validateField('startAddress')"
				></input>
				<view class="error-message" v-if="errors.startAddress">{{ errors.startAddress }}</view>
			  </view>
			
			  <!-- 我要去哪儿 -->
			  <view class="form-item">
				<view class="form-label">我要去哪儿:</view>
				<input 
				  v-model="model1.endAddress" 
				  placeholder="请输入目的地"
				  class="form-input"
				  @blur="validateField('endAddress')"
				></input>
				<view class="error-message" v-if="errors.endAddress">{{ errors.endAddress }}</view>
			  </view>
			
			  <!-- 车型 -->
			  <view class="form-item">
				<view class="form-label">车型:</view>
				<input 
				  v-model="model1.carName" 
				  placeholder="请输入车型"
				  class="form-input"
				  @blur="validateField('carName')"
				></input>
				<view class="error-message" v-if="errors.carName">{{ errors.carName }}</view>
			  </view>
			
			  <!-- 出发时间 -->
			  <view class="form-item">
				<button @click="showTimePicker = true" class="time-btn">选择时间</button>
				<input 
				  v-model="model1.startTime" 
				  placeholder="请选择出发时间"
				  class="form-input"
				  readonly
				  @click="showTimePicker = true"
				></input>
				<view class="error-message" v-if="errors.startTime">{{ errors.startTime }}</view>
			  </view>
			  <!-- 时间选择器弹窗 -->
			  <view class="picker-mask" v-if="showTimePicker" @click="showTimePicker = false"></view>
			  <view class="picker-popup" v-if="showTimePicker">
				<view class="picker-header">
				  <button @click="showTimePicker = false" class="picker-btn cancel">取消</button>
				  <button @click="confirmTime" class="picker-btn confirm">确认</button>
				</view>
				<picker-view
				  :value="pickerValue"
				  @change="onTimeChange"
				  class="picker-view"
				>
				  <picker-view-column>
					<view v-for="year in years" :key="year">{{ year }}年</view>
				  </picker-view-column>
				  <picker-view-column>
					<view v-for="month in months" :key="month">{{ month }}月</view>
				  </picker-view-column>
				  <picker-view-column>
					<view v-for="day in days" :key="day">{{ day }}日</view>
				  </picker-view-column>
				  <picker-view-column>
					<view v-for="hour in hours" :key="hour">{{ hour }}时</view>
				  </picker-view-column>
				  <picker-view-column>
					<view v-for="minute in minutes" :key="minute">{{ minute }}分</view>
				  </picker-view-column>
				</picker-view>
			  </view>
			  <button @click="submitDriverOrder" class="submit-btn">提交订单</button>
			</view>
		</view>
		
		<!-- 我的订单列表 -->
		<view v-if="currentSegment === 2" class="order-list">
			<view class="order-list-container">
				<view class="title">我的订单</view>
				<!-- 订单列表 -->
				<view 
				  v-for="(order, index) in orderList" 
				  :key="index" 
				  class="order-item"
				>
				  <view class="order-info">
					<view class="address">
					  <text class="label">出发地：</text>
					  <text>{{ order.startAddress }}</text>
					  <!-- 导向箭头 -->
					  <text class="arrow"> → </text>
						<text class="label">目的地：</text>
					  <text>{{ order.endAddress }}</text>
					</view>
					<view class="time">
					  <text class="label">时间：</text>
					  <text>{{ order.startTime }}</text>
					</view>
					<view class="orderStatus">
					  <text class="label">状态：</text>
					  <text :class="order.orderStatus === 1 ? 'status-pending' : order.orderStatus === 2 ? 'status-accepted' : 'status-completed'">
						{{ getStatusText(order.orderStatus) }}
					  </text>
						<button v-if="order.orderStatus !== '4'" class="action-btn" @click="cancelOrderAction(order)">取消</button>
						<button v-if="order.orderStatus === '4'" :class="['action-btn', order.isReviewed ? 'reviewed-btn' : '']"
						 @click="reviewOrderAction(order)">{{ order.isReviewed ? '已评价' : '点击评价' }}</button>
					</view>
				  </view>
				</view>
			  </view>
			  <!-- 空状态 -->
			  <view v-if="orderList.length === 0" class="empty">暂无订单</view>
		</view>
	</view>
</template>
<script>
import { submitDriverOrder,listUserOrders,userCancelOrder,getReviewByOrderId } from '@/api/driver/driver';

export default {
  data() {
    return {
	  currentSegment: 1,
      // 表单数据
      model1: {
        startAddress: '',
        endAddress: '',
        carName: '',
        startTime: ''
      },
      // 错误信息
      errors: {},
      // 时间选择器
      showTimePicker: false,
      pickerValue: [],
      years: [],
      months: Array.from({ length: 12 }, (_, i) => i + 1),
      days: Array.from({ length: 31 }, (_, i) => i + 1),
      hours: Array.from({ length: 24 }, (_, i) => i),
      minutes: Array.from({ length: 60 }, (_, i) => i),
	  orderList: [] // 订单列表
    };
  },

  onLoad() {
    // 初始化年份（近10年）
    const currentYear = new Date().getFullYear();
    this.years = Array.from({ length: 10 }, (_, i) => currentYear + i);
    
    // 设置默认时间为当前时间
    const now = new Date();
    this.pickerValue = [
      0, // 年（默认当前年）
      now.getMonth(), // 月
      now.getDate() - 1, // 日
      now.getHours(), // 时
      now.getMinutes() // 分
    ];
  },

  methods: {
    // 验证单个字段
    validateField(field) {
      const errors = { ...this.errors };
      
      if (!this.model1[field]) {
        const messages = {
          startAddress: '请输入出发地址',
          endAddress: '请输入目的地',
          carName: '请输入车型',
          startTime: '请选择出发时间'
        };
        errors[field] = messages[field];
      } else {
        delete errors[field];
      }
      
      this.errors = errors;
      return !errors[field];
    },
	// 切换标签页
	switchSegment(segment) {
	  this.currentSegment = segment;
	  // 切换后加载对应数据
	  this.fetchCurrentSegmentData();
	},
	// 根据当前标签页加载对应数据
	fetchCurrentSegmentData() {
	  if (this.currentSegment === 2) {
		  // 加载全部订单
		  this.getOrderList();
	  } 
	},
    // 验证所有字段
    validateForm() {
      const errors = {};
      
      if (!this.model1.startAddress) errors.startAddress = '请输入出发地址';
      if (!this.model1.endAddress) errors.endAddress = '请输入目的地';
      if (!this.model1.carName) errors.carName = '请输入车型';
      if (!this.model1.startTime) errors.startTime = '请选择出发时间';
      
      this.errors = errors;
      return Object.keys(errors).length === 0;
    },

    // 时间选择器变化
    onTimeChange(e) {
      this.pickerValue = e.detail.value;
    },

    // 确认时间选择
    confirmTime() {
      const [yearIdx, monthIdx, dayIdx, hourIdx, minuteIdx] = this.pickerValue;
      const year = this.years[yearIdx];
      const month = this.months[monthIdx];
      const day = this.days[dayIdx];
      const hour = this.hours[hourIdx];
      const minute = this.minutes[minuteIdx];
      
      // 格式化时间为 YYYY-MM-DD HH:mm:ss
      this.model1.startTime = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00`;
      this.showTimePicker = false;
      this.validateField('startTime');
    },

    // 提交订单
    async submitDriverOrder() {
      if (!this.validateForm()) return;
      
      try {
        await submitDriverOrder(this.model1);
        uni.showToast({ title: '提交订单成功', icon: 'success' });
        // 重置表单
        this.model1 = {
          startAddress: '',
          endAddress: '',
          carName: '',
          startTime: ''
        };
      } catch (err) {
        uni.showToast({ title: err.message || '提交失败', icon: 'none' });
      }
    },
	// 获取订单列表
	async getOrderList() {
	  try {
		const res = await listUserOrders();
		const orders = res.rows || [];
		for(const order of orders){
			try {
				//调用后台接口
				const reviewRes = await getReviewByOrderId(order.orderId);
				// 根据rows数组长度判断是否有评价记录
				order.isReviewed = reviewRes && reviewRes.rows && reviewRes.rows.length > 0;
			} catch (error) {
				order.isReviewed = false;
			}
		}
		this.orderList = orders;
	  } catch (err) {
		uni.showToast({ title: '查询订单失败', icon: 'none' });
	  }
	},
	// 订单状态文字映射
	getStatusText(orderStatus) {
	  const statusMap = {
		'1': '待接单',
		'2': '已接单',
		'4': '已完成',
	  };
	  return statusMap[orderStatus] || '未知';
	},
	//用户取消
	async cancelOrderAction(order) {
	  try {
		  // 抢单：调用抢单接口
		  await userCancelOrder(order.orderId);
		  uni.showToast({ title: '已取消', icon: 'success' });
		  // 刷新订单列表
		  this.getOrderList();
	  } catch (err) {
		uni.showToast({ title: '操作失败', icon: 'none' });
	  }
	},
	
	//评价
	async reviewOrderAction(order) {
	  await uni.navigateTo({
	    url: `/pages/work/driver/driverReview?orderId=${order.orderId}`
	  });
	}
  }
};
</script>

<style scoped>
.order-segment-page {
  padding: 15px;
}

.segment-control {
  display: flex;
  margin-bottom: 15px;
}

.segment-item {
  flex: 1;
  text-align: center;
  padding: 8px 0;
  border: 1px solid #007aff;
  border-radius: 4px;
  margin-right: 5px;
  color: #007aff;
}

.segment-item:last-child {
  margin-right: 0;
}

.segment-item.active {
  background-color: #007aff;
  color: #fff;
}
.order-list {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
}
.order-form-container {
  padding: 20px;
  background-color: #f5f5f5;
}

.form {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 表单项样式 */
.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

/* 标签样式 - 确保文字完整显示 */
.form-label {
  width: 100%;
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  white-space: nowrap;
}

/* 输入框样式 */
.form-input {
  width: 100%;
  height: 0%;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  font-size: 16px;
}

/* 时间选择按钮 */
.time-btn {
  margin-top: 0px;
  padding: 10px;
  background-color: #007aff;
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
}

/* 错误提示 */
.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 48px;
  line-height: 48px;
  background-color: #007aff;
  color: #fff;
  border-radius: 24px;
  font-size: 18px;
  margin-top: 20px;
}

/* 时间选择器弹窗 */
.picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 998;
}

.picker-popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 999;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.picker-btn {
  padding: 8px 16px;
  font-size: 16px;
}

.cancel {
  color: #666;
  background-color: transparent;
}

.confirm {
  color: #007aff;
  background-color: transparent;
}

.picker-view {
  width: 100%;
  height: 300px;
}
.order-list-container {
  padding: 20px;
  background-color: #f5f5f5;
}
.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
}
.order-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.order-info .address,
.order-info .time,
.order-info .orderStatus {
  margin-bottom: 8px;
  font-size: 14px;
}
.label {
  color: #666;
  margin-right: 4px;
}
/* 箭头样式 */
.arrow {
  margin: 0 4px;
  color: #007aff; /* 箭头颜色，可自定义 */
}
.status-pending {
  color: #ff9900;
}
.status-accepted {
  color: #007aff;
}
.status-completed {
  color: hotpink; /* 已接单蓝色 */
}
.empty {
  text-align: center;
  padding: 40px 0;
  color: #999;
}
.action-btn {
  /* 原有按钮样式保留，新增以下优化样式 */
  padding: 6px 12px; /* 调整内边距，控制按钮大小 */
  font-size: 14px; /* 调整字体大小 */
  border: 1px solid #007aff;
  border-radius: 4px;
  background-color: #fff;
  color: #007aff;
  cursor: pointer;
  transition: all 0.3s ease; /* 增加过渡效果，提升交互感 */
}
.action-btn:hover {
  background-color: #007aff;
  color: #fff; /* 鼠标悬浮时变色，增强交互反馈 */
}
.reviewed-btn {
  border-color: #ccc;
  color: #ccc;
  cursor: not-allowed;
  background-color: #f5f5f5; /* 已评价按钮背景设为浅灰，更易区分 */
}
.reviewed-btn:hover {
  background-color: #f5f5f5; /* 已评价按钮悬浮时保持浅灰，无交互变化 */
  color: #ccc;
}
</style>
